package org.example.chat.service.impl;

import com.alibaba.druid.util.StringUtils;
import org.example.chat.api.Constant;
import org.example.chat.dao.RegionInfoRepository;
import org.example.chat.dao.UserRepository;
import org.example.chat.entity.RegionInfo;
import org.example.chat.entity.User;
import org.example.chat.security.entity.LoginUser;
import org.example.chat.service.IUserService;
import org.example.chat.vo.RegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;

/**
 * @author cheval
 */
@Service
public class UserServiceImpl extends BaseService implements IUserService, UserDetailsService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RegionInfoRepository regionInfoRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public List<User> queryAll() {
        return userRepository.findAll();
    }

    @Override
    public int addUser(RegisterVo registerVo) {
        // 1. 判断验证码是否正确
        String value = redisTemplate.opsForValue().get(registerVo.getCaptchaKey());
        if (StringUtils.isEmpty(value)) {
            // 验证码过期
            return 3;
        }
        if (!value.equals(registerVo.getCapture())) {
            // 验证码错误
            return 2;
        }
        // 2. 验证码正确， 添加用户
        User user = new User();
        user.setId(idGenerate.nextId("userId"));
        user.setPassword(passwordEncoder.encode(registerVo.getPassword()));
        user.setCreateDate(LocalDate.now());
        user.setStatus(Constant.USER_STATUS_NORMAL);
        user.setJoinMethod(Constant.ADDED_FOR_FRIEND_METHOD_AGREE);
        String areaName = registerVo.getAreaName();
        user.setAreaName(areaName);
        String[] arr = areaName.split(",");
        if (arr.length == 3) {
            // 省市县, 取县级编码
            setUserAreaCode(user, arr[2]);
        } else if (arr.length == 2) {
            // 省市， 取市级编码
            setUserAreaCode(user, arr[1]);
        } else if (arr.length == 1) {
            // 省， 取省级编码
            setUserAreaCode(user, arr[0]);
        } else {
            user.setAreaCode("xxxxxx");
        }
        user.setUsername(registerVo.getUsername());
        user.setNickname(registerVo.getNickname());
        user.setSex(registerVo.getSex());
        user.setEmail(registerVo.getEmail());
        User save = userRepository.save(user);
        if (save == null) {
            // 添加失败
            return 1;
        }
        return 0;
    }

    /**
     * 根据地区名设置用户所在地区码
     * @param user
     * @param areaName
     */
    private void setUserAreaCode(User user , String areaName) {
        List<RegionInfo> regionInfos = regionInfoRepository.findByName(areaName);
        if (regionInfos != null && regionInfos.size() == 1) {
            user.setAreaCode(regionInfos.get(0).getCode());
        } else {
            // 未知地区
            user.setAreaCode("xxxxxx");
        }
    }

    @Override
    public User queryUserByUsername(String username) {
        return userRepository.findUserByUsername(username);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("账号不存在");
        }
        return new LoginUser(user);
    }




    @Override
    public List<User> queryUserByAccountOrPhone(String key) {
        User user = userRepository.findUserByUsername(key);
        if (user != null) {
            return Arrays.asList(user);
        }
        return null;
    }

    @Transactional
    @Override
    public boolean updateUserHeadImage(String userId, String imgPath, String bigImgPath) {
        int row = userRepository.updateUserHead(userId, imgPath, bigImgPath);
        if (row == 1) {
            return true;
        }
        return false;
    }
}
